package com.practice.question2;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 曾庆红
 * {@code @date} 2023-10-18 19:52
 */

public class MyContainer2<T> {
    private LinkedList<T> list = new LinkedList<>();
    private final int MAx = 10;
    int count = 0;
    private ReentrantLock lock = new ReentrantLock();
    private Condition product = lock.newCondition();
    private Condition consumer = lock.newCondition();
    public void put(T t){
        try{
            lock.lock();
            while(list.size() == 10){
                product.await();
            }
            list.add(t);
            count++;
            consumer.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public T get(){
        T t = null;
        try{
            lock.lock();
            while(list.size() == 0){
                consumer.await();
            }
            t = list.removeFirst();
            count--;
            product.signalAll();
            return t;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
        return t;
    }
}
